window.onload=initall;
countText=1;

function initall(){
	
	document.getElementById("type").selectIndex=0;	
	document.getElementById("type").onchange=showSub;
	document.getElementById("typeE").onchange=showSubE;
	document.getElementById("subsec").style.visibility="hidden";
	  document.getElementById("remlink").style.visibility="hidden";
	document.getElementById("newadd").onclick=createNode;
	document.getElementById("remlink").onclick=remNode;
	document.getElementById("newadd2").onclick=createNodeE;
	document.getElementById("remlink2").onclick=remNodeE;
	document.getElementById("t1").value="";
	titleText();
}
titleChk=0;

function titleplus(){
	if(titleChk==0){
		getElement("title").value="";
	}
}

function titleText(){
	getElement("title").value="Enter Form Name";
}
function titleminus(){
	k=trim(getElement("title").value);
	if(k==""){
		titleChk=0;	
		titleText();
	}
	else{
		titleChk=1;	
	}
}

function showSub(){
	
	 typ=document.getElementById("type").value;
	//document.getElementById("t1").value="";
	 invisSub("subsec","remlink");
	 switch(typ){
		case '1':
				break;
		
		case '2':
				break;
				
		case '3':
				break;
				
		case '4':	
				//break;
				
		case '5':
					//break;
				
		case '6':visSub("subsec");
				break;
	 }
	
	
}
function showSubE(){
	 typ=document.getElementById("typeE").value;
	document.getElementById("e1").value="";
	invisSubE("subsec2","remlink2");
	document.getElementById("modifiable2").innerHTML=" ";
	 
	 switch(typ){
		case '1':
				break;
		
		case '2':
				break;
				
		case '3':
				break;
				
		case '4':	
				//break;
				
		case '5':
					//break;
				
		case '6':visSub("subsec2");
				break;
	 }
}
function visSub(divid){
	document.getElementById(divid).style.visibility="visible";
}

function invisSub(divid,remL){
	document.getElementById(divid).style.visibility="hidden";
	
	for(i=1;i<=countText;i++){
		remNode();	
	}
	countText=1;
	 document.getElementById(remL).style.visibility="hidden";
}
function invisSubE(divid,remL){
	document.getElementById(divid).style.visibility="hidden";
	
	for(i=1;i<=countText;i++){
		remNodeE();	
	}
	countText=1;
	 document.getElementById(remL).style.visibility="hidden";
}

function createN(nme,remL,divname){
	
	countText++;
	var labela= document.createElement("label");
	labela.appendChild(document.createTextNode((countText)+"."));
	labela.className="label2";
	var textboxa=document.createElement("input");
	textboxa.setAttribute("style","text");
	textboxa.className="textbox";
	textboxa.name=nme+(countText);
	textboxa.id=nme+(countText);
	
	var newdiv=document.createElement("div");
	newdiv.className="optfield";
	newdiv.id= divname+(countText);
	newdiv.appendChild(labela);
	newdiv.appendChild(textboxa);
	
	
	if(countText>1)
	{
	document.getElementById(remL).setAttribute("style","visibility:visible");
	}
	
	return newdiv;
}


function createNode()
{
	
	
	newdiv=createN("t","remlink","newdv");
	
	var divbody=document.getElementById("modifiable");
	
	divbody.appendChild(newdiv);
	
	return false;
}
function remN(node,remL,divname){
	if(countText>1)
	{
		var divno=divname+countText;
		var child=document.getElementById(divno);
		document.getElementById(node).removeChild(child);
		countText--;
		if(countText<2)
		{
		 document.getElementById(remL).setAttribute("style","visibility:hidden");
		}
	}
	
}
function remNode()
{
	
	remN("modifiable","remlink","newdv");
	
	return false;
}
function createNodeE(){
	newdiv=createN("e","remlink2","newd");
	
	var divbody=document.getElementById("modifiable2");
	
	divbody.appendChild(newdiv);
	
}

function remNodeE(){
	
	remN("modifiable2","remlink2","newd");
}

function trim(str){
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

}

countElement=0;
sections = [];
var opt =new Array();
function addElement(){
	
	var Qtitle=document.getElementById("qtitle").value;	
	
	var helpT=document.getElementById("helpT").value;	
	var typee=document.getElementById("type").value;	
	var reqd=document.getElementById("reqd");
	//alert("h"+reqd+"h");
	
	if(trim(Qtitle)==""){
		alert("Enter the question title");	
		return;
	}
	//Validation here!!!
	/*
	
	*/
	//var name = "Drag Me";
	newdiv=subAddFunction(Qtitle,helpT,typee,reqd,'t');
	if(newdiv==null){
		return;	
	}
	newdiv3=document.createElement("div");
	newdiv3.appendChild(newdiv);
	newdiv3.className="handle";
	
	var newdiv2 = Builder.node('div', {id: 'group' + (sections.length + 1), className: 'section', style: 'display:none;' }, [
				//Builder.node('h3', {className: 'handle'}, "Drag-Me")
				newdiv3
			]);
	
	
	//del.style.left="90%";
	//del.style.top="10%";
	
	
	newdiv2.appendChild(newdiv3);
	newdiv2.onmouseover=disOpt;
	newdiv2.onmouseout=hidOpt;
	$('createdF').appendChild(newdiv2)
	//place.appendChild(newdiv2);
	//newdiv2.style.display="none";
	sections.push(newdiv2.id);
	Effect.Appear(newdiv2.id);
	//alert("d");
	destroyLineItemSortables();
	createLineItemSortables();
	createGroupSortable();
	
}

function subAddFunction(Qtitle,helpT,typee,reqd,box){
	
	var newdiv=document.createElement("div");
	if(!reqd.checked){
		newdiv.className="optfield";
	}
	else{
		newdiv.className="reqfield";
	}
	
	var labela= document.createElement("label");
	labela.appendChild(document.createTextNode(Qtitle+": "));
	labela.className="label2";
	//---------------hidden variables------------------------
	var ty=document.createElement("input");
	ty.type="hidden";
	ty.id="type"+(sections.length + 1);
	ty.value=typee;
	newdiv.appendChild(ty);
	ty=document.createElement("input");
	ty.type="hidden";
	ty.id="title"+(sections.length + 1);
	ty.value=Qtitle;
	newdiv.appendChild(ty);
	ty=document.createElement("input");
	ty.type="hidden";
	ty.id="help"+(sections.length + 1);
	ty.value=helpT;
	newdiv.appendChild(ty);
	ty=document.createElement("input");
	ty.type="hidden";
	ty.id="reqd"+(sections.length + 1);
	if(!reqd.checked){
		ty.value="";
	}
	else{
		ty.value="reqd";
	}
	
	newdiv.appendChild(ty);
	//--------------------------------------------
	var element2;
	/*
	if(typee=='6'||typee=='4'||typee=='5'){
		if(trim(document.getElementById(box+'1').value)==""){
			alert("option 1 compulsory");
			return;
		}
		k=0;
		opt.length=0;
		for(i=1;i<=countText;i++){
			if(trim(document.getElementById(box+i).value)!=""){
				opt[k++]=trim(document.getElementById(box+i).value);
				//alert(opt[i]);
			}
		}
		
		var op=document.createElement("input");
		op.type="hidden";
		op.id="opt"+(sections.length + 1);
		op.value=opt.length;
		
	}*/
	subOpt(Qtitle,helpT,typee,reqd,box);
	switch(typee){
		case '1':element2=createText("","",helpT);
					
				break;
		
		case '2':element2=createTextA("","",helpT);
				break;
				
		case '3':element2=createTextPas("","",helpT);
				break;
				
		case '4':element2=createCheck("","",helpT);	
				break;
				
		case '5':element2=createRadio("","",helpT);
					break;
								
		case '6': element2=createList("","",helpT);
				break;
		
	}
	
	del=document.createElement("div");
	del.className="delete";
	del.title="Delete";
	del.id='d'+(sections.length + 1);
	del.style.display="none";
	del.appendChild(document.createTextNode("_"));
	del.onclick=delElement;
	edt=document.createElement("div");
	edt.className="edit";
	edt.title="Edit";
	edt.id='x'+(sections.length + 1);
	edt.style.display="none";
	edt.appendChild(document.createTextNode("_"));
	edt.onclick=editElement;
	newdiv.appendChild(edt);
	newdiv.appendChild(del);
	
	
	newdiv.id= "newdiv"+(sections.length + 1);
	++countElement;
	newdiv.appendChild(labela);
	newdiv.appendChild(element2);
	
	
	return newdiv;
}

function subOpt(Qtitle,helpT,typee,reqd,box){
	
	if(box=="ext"){
		opt.length=0;
		opt=optionz;
	}
	//------
	else{
	if(typee=='6'||typee=='4'||typee=='5'){
		if(trim(document.getElementById(box+'1').value)==""){
			alert("option 1 compulsory");
			return;
		}
		k=0;
		opt.length=0;
		for(i=1;i<=countText;i++){
			if(trim(document.getElementById(box+i).value)!=""){
				opt[k++]=trim(document.getElementById(box+i).value);
				//alert(opt[i]);
			}
		}
		
		var op=document.createElement("input");
		op.type="hidden";
		op.id="opt"+(sections.length + 1);
		op.value=opt.length;
		
	}	
	}
	//---------
}

function changeIds(len,num){
	document.getElementById("group"+(len)+"").id="group"+(num);
		changeId(len,num);
	
}
function changeId(len,num){
	document.getElementById("d"+(len)).id="d"+num;
		document.getElementById("x"+(len)).id="x"+num;
		document.getElementById("newdiv"+(len)).id="newdiv"+num;
		document.getElementById("type"+(len)).id="type"+num;
		document.getElementById("title"+(len)).id="title"+num;
		document.getElementById("help"+(len)).id="help"+num;
		document.getElementById("reqd"+(len)).id="reqd"+num;
		if(document.getElementById("opt"+(len)))
		document.getElementById("opt"+(len)).id="opt"+num;
}

function delElement(){
	ide=this.id;
	
	num=ide.substr(1);
	d=document.getElementById('group'+num);
	//alert(id+" "+num);
	document.getElementById('createdF').removeChild(d);	
	//alert(sections.length);
	if(num<sections.length){
		changeIds((sections.length),num);
		//alert(sections.length);
	}
	for(i=0;i<sections.length;i++){
		//alert(sections[i]);
	}
	sections.splice(sections.indexOf("group"+(sections.length)),1);
	destroyLineItemSortables();
	createLineItemSortables();
	createGroupSortable();
}

function getElement(id){
	return(document.getElementById(id));	
}
countBkp=1;
function editElement(){
	showGrey();
	showEdit()
	ide=this.id;
	num=ide.substr(1);
	countBkp=countText
	countText=1;
	getElement("qtitleE").value=getElement("title"+num).value;
	getElement("helpTE").value=getElement("help"+num).value;
	getElement("typeE").selectedIndex=parseInt(getElement("type"+num).value)-1;
	getElement("id").value=num;
	//alert(getElement("reqd"+num).value);
	if(getElement("reqd"+num).value=="reqd"){
		getElement("reqdE").checked="checked";	
	}
	t=getElement("type"+num).value
	if(t=="1"||t=="2"||t=="3"){
		hideEditList();
	}
	else{
		if(parseInt(getElement("opt"+num.value))==1){
			getElement("remlink2").style.visibility="hidden";
			getElement("subsec2").style.visibility="hidden";
		}else{
				getElement("remlink2").style.visibility="visible";
				getElement("subsec2").style.visibility="visible";
		}
		var opts=new Array();
		switch(t){
			case '4':	
						
			case '5':	opts=getCandR('newdiv'+num);
						break;
			case '6':	opts=getSelectList('newdiv'+num);
						break;
		}
		
		
		
		for(i=1;i<opts.length;i++){
			createNodeE();
		}
		for(i=0;i<opts.length;i++){
			getElement("e"+(i+1)).value=opts[i];	
		}
		//getElement("e1").value="hello";
	}
}

function editElementFun(){
	var Qtitle=document.getElementById("qtitleE").value;	
	
	var helpT=document.getElementById("helpTE").value;	
	var typee=document.getElementById("typeE").value;	
	var reqd=document.getElementById("reqdE");
	//alert("h"+reqd+"h");
	num=getElement("id").value;
	if(trim(Qtitle)==""){
		alert("Enter the question title");	
		return;
	}
	//Validation here!!!
	/*
	
	*/
	//var name = "Drag Me";
	newdiv=subAddFunction(Qtitle,helpT,typee,reqd,'e');
	if(newdiv==null){
		return;	
	}
	
	b=getElement("group"+num).getElementsByClassName("handle");
	for(i=0;i<b.length;i++){
		b[i].innerHTML="";
		b[i].appendChild(newdiv);
	}
	//alert(num);
	changeId((sections.length+1),num);
	
	hideEdit();
	 
	
}
function getCandR(id){
	var s=getElement(id).getElementsByTagName("label");
	var opts=new Array();
	
	for(k=1;k<s.length;k++){
		opts[k-1]=s[k].innerHTML;
		
	}
	return opts;
}	

function getSelectList(id){
	var s=getElement(id).getElementsByTagName("option");
	var opts=new Array();
	
	for(k=0;k<s.length;k++){
		opts[k]=s[k].innerHTML;
		
	}
	//alert(opts[0]);
	return opts;
}
function hideEditList(){
	getElement("subsec2").style.visibility="hidden";
	getElement("remlink2").style.visibility="hidden";
	
}

function showGrey(){
	document.getElementById("grey").style.visibility="visible";	
}

function hideGrey(){
	document.getElementById("grey").style.visibility="hidden";	
}
function showEdit(){
	document.getElementById("edit").style.visibility="visible";	
}

function hideEdit(){
	invisSubE("subsec2","remlink2");
	hideGrey();
	hideEditList();
	
	document.getElementById("edit").style.visibility="hidden";	
	countText=countBkp; // backup of countText variable whch is my "system" variable
}
function disOpt(){
	
	ide=this.id;
	num=ide.substr(5);
	
	document.getElementById("d"+num).style.display="block";
	document.getElementById("x"+num).style.display="block";
	//alert(num);
}
function hidOpt(){
	ide=this.id;
	
	num=ide.substr(5);
	
	document.getElementById("d"+num).style.display="none";
	document.getElementById("x"+num).style.display="none";
	//alert(num);
}
//----------------------------------------------------------------
//Drag functions

	function createLineItemSortables() {
		for(var i = 0; i < sections.length; i++) {
			Sortable.create(sections[i],{tag:'div',dropOnEmpty: true, containment: sections,only:'lineitem'});
		}
	}

	function destroyLineItemSortables() {
		for(var i = 0; i < sections.length; i++) {
			Sortable.destroy(sections[i]);
		}
	}

	function createGroupSortable() {
		Sortable.create('createdF',{tag:'div',only:'section',handle:'handle'});
	}

	/*
	Debug Functions for checking the group and item order
	*/
	function getGroupOrder() {
		var sections = document.getElementsByClassName('section');
		var alerttext = '';
		sections.each(function(section) {
			var sectionID = section.id;
			var order = Sortable.serialize(sectionID);
			alerttext += sectionID + ': ' + Sortable.sequence(section) + '\n';
		});
		alert(alerttext);
		return false;
	}

//----------------------------------------------------------------
// create functions
function createText(name,id,help){
	element2=document.createElement("input");
	element2.type="text";
	element2.className="textbox";
	element2.title=help;
	//element.name="";
	//element.id="";
	
	return element2;
}
function createTextPas(name,id,help){
	element2=document.createElement("input");
	element2.type="password";
	element2.className="textbox";
	element2.title=help;
	//element.name="";
	//element.id="";
	
	return element2;
}
function createTextA(name,id,help){
	element2=document.createElement("textarea");
	
	element2.className="textbox3";
	element2.title=help;
	//element.name="";
	//element.id="";
	
	return element2;
}

function createList(name,id,help){
	element2=document.createElement("select");
	for(i=0;i<opt.length;i++){
		el=	document.createElement("option");
		el.text=opt[i];
		//alert(opt[i]);
		element2.options.add(el);
	}
	return element2;
	
}

function createRadio(name,id,help){
	element2=document.createElement("div");
	
	for(i=0;i<opt.length;i++){
		labela= document.createElement("label");
		labela.appendChild(document.createTextNode(opt[i]));
		labela.className="label3";
		r=document.createElement("input");
		r.type="radio";
		r.name=name;
		element2.appendChild(labela);
		element2.appendChild(r);
	}
	return element2;
}

function createCheck(name,id,help){
	element2=document.createElement("div");
	
	for(i=0;i<opt.length;i++){
		labela= document.createElement("label");
		labela.appendChild(document.createTextNode(opt[i]));
		labela.className="label3";
		r=document.createElement("input");
		r.type="checkbox";
		r.name=name+i;
		element2.appendChild(labela);
		element2.appendChild(r);
	}
	return element2;	
	
}


//--------------------------------Save Functions---------------------------------------------------
function xmlhttp(){
		var xhr;
	
	try{
		xhr= new XMLHttpRequest();
	}
	catch(error){
		try{
			xhr= new ActiveXObject('Microsoft.XMLHTTP');
		}
		catch(error){
			xhr=null;
		}
	}
	return xhr;
}

divs=new Array();
f_id=-1;
function save(){
	if(titleChk==0){
		alert("Enter form name");	
		return;
	}
	f_title=getElement("title").value;
	var r=document.getElementsByClassName("section");
	
	if(r.length==0){
		alert("Add some element");
		return;
	}
	divs.length=0;
	for(i=0;i<r.length;i++){
		//alert(r[i].id);	
		divs[i]=r[i].id.substr(5);
		//alert(divs[i]);
	}
		//alert(createParam());
		
		
	var xhr=xmlhttp();
	if(xhr!=null){
		//var url="";
		var url="/form/save?";
		
		var params="f_id="+f_id+"&f_title="+f_title+"&"+createParam();
		//params="hi=hi";
		alert(params);
		xhr.open('POST',url,true);
		
		xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		xhr.setRequestHeader("Content-length", params.length);
		xhr.setRequestHeader("Connection", "close");
		xhr.onreadystatechange = function () {
			if(xhr.readyState == 4) {
				if(xhr.status==200 || xhr.status== 304){
					
					f_id=trim(xhr.responseText);
					
				}
				else{
				
				}
			
			}
		};
		
		xhr.send(params);	
		
	}
}

function createParam(){
	
	var str="";
	str="max="+divs.length+"&";
	for(i=0;i<divs.length;i++){
		num=divs[i];
		alert(num);
		qtitle=getElement("title"+num).value;
		title=getElement("help"+num).value;
		var req;
		typee=parseInt(getElement("type"+num).value);
		if(getElement("reqd"+num).value=="reqd")
			req=1;
		else
			req=0;
		var ty;
		if(typee=='1'||typee=='2'||typee=='3'){
			tp=0;	
		}
		else{
			tp=1;
		}
		str+="e"+i+"="+tp+"&qt"+i+"="+qtitle+"&tt"+i+"="+title+"&re"+i+"="+req+"&ty"+i+"="+typee+"&";
		var opts=new Array();

		switch(typee){
			case 4:	
						
			case 5:	opts=getCandR('newdiv'+num);
					
						break;
			case 6:	opts=getSelectList('newdiv'+num);
						break;
		}
		if(opts.length>0){
			str+="op"+i+"="+opts.length+"&";	
		}
		//alert(opts.length);
		for(j=0;j<opts.length;j++){
			str+="e"+i+j+"="+opts[j]+"&";
			
		}
		
		
	}
	
	return str;
}

function findQues(){
	txt=getElement("qt").value;
	if(trim(txt)==""){
		return;	
	}
	
	var xhr=xmlhttp();
	if(xhr!=null){
		//var url=
		
		var params="str="+txt+"&";
		//params="hi=hi";
		//alert(params);
		xhr.open('POST',url,true);
		
		xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		xhr.setRequestHeader("Content-length", params.length);
		xhr.setRequestHeader("Connection", "close");
		xhr.onreadystatechange = function () {
			if(xhr.readyState == 4) {
				if(xhr.status==200 || xhr.status== 304){
					
					getElement("suggest").innerHTML=xhr.responseText;
					document.getElementById("suggest").style.visibility="visible";
					
					
					var l=getElement("suggest").getElementsByTagName("li");
					for(z=0;z<l.length;z++){
						l[z].onclick=selectQues;	
					}
				}
				else{
				
				}
			
			}
		};
		
		xhr.send(params);	
		
	}
	
}
var optionz=new Array();
var quesA,hlpA,typA,reqA;
function selectQues(){
		
	ee_id=this.id;
	ff_id=this.className;
	textA=this.innerHTML;
	var xhr=xmlhttp();
	if(xhr!=null){
		//var url=;
		//url="hi.html";
		
		var params="form="+ff_id+"&element="+ee_id+"&";
		//params="hi=hi";
		//alert(params);
		xhr.open('POST',url,true);
		
		xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		xhr.setRequestHeader("Content-length", params.length);
		xhr.setRequestHeader("Connection", "close");
		xhr.onreadystatechange = function () {
			if(xhr.readyState == 4) {
				if(xhr.status==200 || xhr.status== 304){
					//alert(xhr.responseText);
					var el=xhr.responseXML.getElementsByTagName("root")[0];
					quesA=getVal(xhr.responseXML,"question");
					hlpA=getVal(xhr.responseXML,"help");
					typA=getVal(xhr.responseXML,"type");
					reqA=getVal(xhr.responseXML,"reqd");
					
					optionz.length=0;
					if(typA=='4'||typA=='5'||typA=='6'){
						var op=xhr.responseXML.getElementsByTagName("element");
						for(y=0;y<op.length;y++){
							optionz[y]=op[y].firstChild.nodeValue;
							alert(optionz[y]);
						}
					}
					
					getElement("qt").value=textA;
					document.getElementById("suggest").style.visibility="hidden";
				}
				else{
				
				}
			
			}
		};
		
		xhr.send(params);	
		
	}
	
}
function addEElemet(){
	newdiv=subAddFunction(quesA,hlpA,typA,reqA,'ext');
	if(newdiv==null){
		return;	
	}
	newdiv3=document.createElement("div");
	newdiv3.appendChild(newdiv);
	newdiv3.className="handle";
	
	var newdiv2 = Builder.node('div', {id: 'group' + (sections.length + 1), className: 'section', style: 'display:none;' }, [
				//Builder.node('h3', {className: 'handle'}, "Drag-Me")
				newdiv3
			]);
	
	
	//del.style.left="90%";
	//del.style.top="10%";
	
	
	newdiv2.appendChild(newdiv3);
	newdiv2.onmouseover=disOpt;
	newdiv2.onmouseout=hidOpt;
	$('createdF').appendChild(newdiv2)
	//place.appendChild(newdiv2);
	//newdiv2.style.display="none";
	sections.push(newdiv2.id);
	Effect.Appear(newdiv2.id);
	//alert("d");
	destroyLineItemSortables();
	createLineItemSortables();
	createGroupSortable();
	
	quesA="";
	hlpA="";
	typA="";
	reqA=""
	optionz.length=0;
	
}
function getVal(theData,theTag){
	if(theData.getElementsByTagName(theTag)[0].firstChild)
	return theData.getElementsByTagName(theTag)[0].firstChild.nodeValue;	
	else
	return "";
}

function hideQues(){
		
		//document.getElementById("suggest").style.visibility="hidden";
}
//---------------------------------------------------------------------------------------------------
